package com.wzm.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

/**
 * 登录拦截
 */
@Component
public class LoginFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String uri = request.getRequestURI();
        if(uri.endsWith("login") || uri.endsWith("register")){
            return false;
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        response.setContentType("application/json;charset=UTF-8");
        String token = request.getHeader("token");
        if(token==null){
            HashMap<String, Object> map = new HashMap<>();
            map.put("success",false);
            map.put("msg","请登录");
            try {
                PrintWriter writer = response.getWriter();
                String s = JSON.toJSONString(map);
                writer.write(s);
                // 2.阻止后续filter执行
                RequestContext.getCurrentContext().setSendZuulResponse(false);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
